<script setup lang="ts">
import MList from "@/components/MList.vue"
import {
    useMessage,
    NTag,
    NIcon, NButton, NPopselect, NUploadDragger, NUpload,
    type DataTableColumns, type UploadFileInfo,
    NPopconfirm
} from 'naive-ui';
import { type RowData } from 'naive-ui/es/data-table/src/interface';
import { ref, h, onMounted } from 'vue';

import { CloudUploadOutline } from "@vicons/ionicons5";
import { Edit, Delete } from "@vicons/carbon"
import useTime from "~/utils/Time";
let { format } = useTime()

import { useFeature } from "~/common/mixins/";
let { LoadOne, DeleteOne, Pagination } = useFeature()

let listRef = ref();
let root = 'basedata';

let columns = ref<DataTableColumns<RowData>>([
    {
        type: 'selection'
    }, {
        title: "数据归属",
        key: "fdType",
        render(rowData, _) {
            switch (rowData.fdType) {
                case "business_type":
                    return "业务类型";
                case "house_type":
                    return "房屋类型";
            }
        },
    }, {
        title: "数据名称",
        key: "fdKey"
    }, {
        title: "数据值",
        key: "fdValue"
    }, {
        title: "状态",
        width: 80,
        key: "fdStatus",
        render(rowData, _) {
            return h(NTag, { type: (rowData.fdStatus == 1 ? "success" : "error") }, "正常");
        }
    }, {
        title: "创建时间",
        key: "fdCreatedAt",
        width: 160,
        render(rowData, _) {
            return format(rowData.fdCreatedAt)
        }
    }, {
        title: '操作',
        key: "action",
        width: 110,
        render(rowData, _) {
            return [h(NButton, {
                circle: true, renderIcon() {
                    return h(NIcon, {}, {
                        default: () => h(Edit)
                    });
                }, type: "primary", style: "margin-right:10px;", onClick(_) {
                    LoadOne(basedata, root, rowData.fdId).then(() => {
                        onShow(rowData);
                    })

                },
            }, ""), renderDeleteIcon(rowData.fdId)]
        }
    }
]);

const renderDeleteIcon = (id: any) => {
    return h(NPopconfirm, {
        onPositiveClick: () => {
            DeleteOne(basedata, root, id).then(() => {
                message.success("删除成功");
                handleQuery();
            })
        },
        negativeText: '取消',
        positiveText: '删除'
    }, {
        trigger: () => h(NButton, {
            circle: true, renderIcon() {
                return h(NIcon, {}, {
                    default: () => h(Delete)
                });
            }, type: "error"
        }, ""),
        default: "确认要删除这行数据？"
    })
}

let importData = ref("")
let file = ref();

let handleChange = (options: { fileList: UploadFileInfo[] }) => {
    file.value = options.fileList[0]?.file;
}

import { useBasedataStore } from "@/store/data/basedataStore";
let basedata = useBasedataStore();

import { } from "naive-ui";
let message = useMessage();

let _importData = () => {
    basedata.importData(file.value).then(_ => {
        message.success("导入成功")
    }).catch(e => {
        message.success("导入失败，异常信息为：" + e);
    })
}

let handleQuery = () => {
    listRef.value?.handleQuery(basedata, root);
}

onMounted(() => {
    handleQuery();
})

let downloadTemplet = () => {
    const link = document.createElement("a");
    link.href = '/templet/ImportBasedata.xls?t=${Date.now()}' // public目录下的路径
    link.download = 'ImportBasedata.xls' // 自定义下载文件名

    link.onerror = () => {
        console.error('文件加载失败')
        URL.revokeObjectURL(link.href)
    }

    // 模拟点击下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}

import EditBasedata from "./component/editBasedata.vue";
let editBasedataRef = ref();

let onShow = (row: any) => {
    editBasedataRef.value?.openDialog(row);
}


</script>

<template>
    <div class="mc_1">
        <MList ref="listRef" :title="'基础数据'" @on-load="handleQuery" @on-show="onShow({ fdStatus: 1 })"
            :total="Pagination.ListTotal" :columns="columns" :data="Pagination.ListData">
            <template #extra_btn>
                <div class="extra_btn">
                    <n-button type="warning" @click="downloadTemplet">下载数据模板</n-button>

                    <n-popselect v-model:value="importData" :options="[]" trigger="click">
                        <n-button type="tertiary">导入数据</n-button>
                        <template #empty>
                            <div class="row">
                                <n-upload @change="handleChange" :default-upload="false" directory-dnd action="#"
                                    :max="5">
                                    <n-upload-dragger>
                                        <div style="margin-bottom: 12px">
                                            <n-icon size="60" :depth="3">
                                                <CloudUploadOutline />
                                            </n-icon>
                                        </div>
                                        <n-text style="font-size: 16px;color: #333!important;">
                                            点击或者拖动文件到该区域来上传
                                        </n-text><br />
                                        <n-p depth="3" style="margin: px 0 0 0;color: #999!important;">
                                            请先下载模板，在模板中添加内容在提交文件导入数据
                                        </n-p>
                                    </n-upload-dragger>
                                </n-upload>

                                <n-button type="primary" @click="_importData">导入数据</n-button>
                            </div>
                        </template>
                    </n-popselect>
                </div>
            </template>

        </MList>

        <EditBasedata ref="editBasedataRef" @handle-query="handleQuery"></EditBasedata>
    </div>


</template>

<style scoped>
.toolbar {
    padding: 10px 0 10px 10px;

    .n-button:first-child {
        margin-right: 10px;
    }
}
</style>
